<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  useMessage,
  NFlex,
  NAvatar,
  NSelect,
  NInputNumber,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { getToken } from '@/utils'
import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

defineOptions({ name: '沙龙配置' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from '@/assets/images/mz.jpg'

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '沙龙',
  initForm: {
    interval: 30,
    sort: 0,
  },
  doCreate: api.createSettingSalon,
  doUpdate: api.updateSettingSalon,
  doDelete: api.deleteSettingSalon,
  refresh: () => $table.value?.handlerefresh(),
})
const data = reactive({
  token: getToken(),
  uploadAction: base_path + 'api/appointment/salon/file',
  deptOption: [],
  gotypeData: [
    {
      label: '内部沙龙',
      value: 1,
    },
    {
      label: '外部沙龙',
      value: 2,
    },
  ],
  sltypeData: [
    {
      label: '会员沙龙',
      value: 1,
    },
    {
      label: '微美沙龙',
      value: 2,
    },
  ],
  InstiumentData: [],
  customer_level: [],
  CityData: [],
  upload: null,
  fileListLength: 0,
  fileList: [],
})
onMounted(() => {
  api.getCustomerLevel().then((res) => (data.customer_level.value = res.data))
  api.getInstrumentList().then((res) => (data.InstiumentData.value = res.data))
  api.getSettingCity().then((res) => (data.CityData.value = res.data))
  $table.value?.handleSearch()
})
function level_format_role(level) {
  let ret = ''
  if (!data.customer_level.value) {
    return
  }
  data.customer_level.value.forEach((item) => {
    if (item.value === level) {
      ret = item.label
    }
  })
  return ret
}
function level_format(level, data) {
  let ret = ''
  if (data) {
    data.forEach((item) => {
      if (item.value === level) {
        ret = item.label
      }
    })
  }

  return ret
}
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '名称',
    key: 'name',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '排序',
    key: 'sort',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '封面图',
    key: 'picture',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NFlex, {}, [
        h(NAvatar, {
          src: row.picture,
          width: 30,
          fallbackSrc: default_image,
        }),
      ])
    },
  },
  {
    title: '城市',
    key: 'city_id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(
        NTag,
        { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
        { default: () => level_format(row.city_id, data.CityData.value) }
      )
    },
  },
  {
    title: '举办人数',
    key: 'number',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '已预约',
    key: 'number_have',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '显示增加',
    key: 'show_add',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '举办时间',
    key: 'date',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
  },

  {
    title: '状态',
    key: 'status',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.status,
        loading: !!row.publishing,
        checkedValue: true,
        uncheckedValue: false,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleEdit(row)
                if (!modalForm.value.files) {
                  modalForm.value.files = []
                }
                data.fileList.value = [
                  {
                    id: 1,
                    name: '封面',
                    url: row.picture,
                    status: 'finished',
                  },
                ]
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/content/contents/update']]
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ data_id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/content/contents/delete']]
              ),
            default: () => h('div', {}, '确定删除该数据吗?'),
          }
        ),
      ]
    },
  },
]

async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.status = row.status === false ? true : false
  row.publishing = false
  try {
    await api.updateSettingSalon(row)
    $message?.success(row.status ? '正常' : '禁用')
    $table.value?.handleSearch()
  } catch (err) {
    // 有异常恢复原来的状态
    row.status = row.status === false
  } finally {
    row.publishing = false
  }
}

const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入标题',
      trigger: ['input', 'blur'],
    },
  ],
}

//图文信息
const message = useMessage()
const customRequestMethod1 = (options) => {
  const { file } = options.file
  const formData = new FormData()
  formData.append('file', file)
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
    .then((response) => response.json())
    .then((data) => {
      console.log(data, 'datatat')
      if (data.code == 200) {
        modalForm.value.picture = data.data.url
        message.success('封面图上传成功')
        options.onProgress(data)
      } else {
        message.error(data.msg)
      }
    })
}
const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}

async function addDepts() {
  data.fileList.value = []
  handleAdd()
}
</script>

<template>
      <CommonPage show-footer title="沙龙列表">
        <template #action>
          <NButton
            v-permission="'post/api/content/contents/create'"
            type="primary"
            @click="addDepts"
          >
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建沙龙
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getSettingSalon"
          :scroll-x="1500"
        >
          <template #queryBar>
            <QueryBarItem label="名称" :label-width="40">
              <NInput
                v-model:value="queryItems.name"
                clearable
                type="text"
                placeholder="请输入名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>
          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
          style="width: 800px !important"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="120"
            :model="modalForm"
            :rules="validateAddUser"
          >
            <n-card content-style="padding: 0;">
              <n-tabs type="line" size="large" :tabs-padding="20" pane-style="padding: 20px;">
                <n-tab-pane name="基本信息">
                  <NFlex justify="space-between">
                    <NFormItem label="沙龙名称" path="name" style="width: 100%">
                      <NInput
                        v-model:value="modalForm.name"
                        clearable
                        placeholder="请输入沙龙名称"
                      />
                    </NFormItem>
                    <NFormItem label="沙龙英文名称" path="english_name" style="width: 100%">
                      <NInput
                        v-model:value="modalForm.english_name"
                        clearable
                        placeholder="请输入英文名称"
                      />
                    </NFormItem>
                    <NFormItem label="排序" path="sort">
                      <NInputNumber
                        style="width: 200px"
                        v-model:value="modalForm.sort"
                        clearable
                        placeholder="输入排序"
                        :default-value="0"
                      />
                    </NFormItem>

                    <NFormItem label="可预约角色类型" path="role_id">
                      <NSelect
                        multiple
                        style="width: 200px"
                        v-model:value="modalForm.role_id"
                        :options="data.customer_level.value"
                        placeholder="请选择角色类型"
                      />
                    </NFormItem>

                    <NFormItem label="举办日期" path="date">
                      <n-date-picker
                        v-model:formatted-value="modalForm.date"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetime"
                        placeholder="选择举办时间"
                        clearable
                      />
                    </NFormItem>
                    <NFormItem label="城市" path="city_id">
                      <NSelect
                        style="width: 200px"
                        v-model:value="modalForm.city_id"
                        :options="data.CityData.value"
                        placeholder="请选择所属城市"
                      />
                    </NFormItem>

                    <NFormItem label="举办地址" path="location" style="width: 100%">
                      <NInput
                        v-model:value="modalForm.location"
                        clearable
                        placeholder="请输入举办地址"
                      />
                    </NFormItem>

<!--                    <NFormItem label="是否开通使用" path="status">-->
<!--                      <NSwitch-->
<!--                        v-model:value="modalForm.status"-->
<!--                        :checked-value="true"-->
<!--                        :unchecked-value="false"-->
<!--                        :default-value="false"-->
<!--                        ><template #checked>是</template><template #unchecked>否</template>-->
<!--                      </NSwitch>-->
<!--                    </NFormItem>-->

                    <NFormItem label="头像封面" path="picture" style="width: 100%">
                      <NUpload
                        :action="data.uploadAction"
                        :headers="{ token: data.token }"
                        :max="1"
                        :custom-request="customRequestMethod1"
                        list-type="image-card"
                        v-model:file-list="data.fileList.value"
                        :show-file-list="true"
                      >
                      </NUpload>
                    </NFormItem>
                    <NFormItem label="介绍组图" path="content_pic" style="width: 100%">
                      <NUpload
                        :action="data.uploadAction"
                        :headers="{ token: data.token }"
                        multiple
                        list-type="image-card"
                        @finish="handleFinish"
                        v-model:file-list="modalForm.content_pic"
                      >
                      </NUpload>
                    </NFormItem>
                  </NFlex>
                </n-tab-pane>
                <n-tab-pane name="附加信息">
                  <NFlex justify="space-between">
                    <NFormItem label="内外场" path="kind">
                      <n-radio-group v-model:value="modalForm.type" name="radiogroup">
                        <n-space>
                          <n-radio
                            v-for="song in data.gotypeData"
                            :key="song.value"
                            :value="song.value"
                          >
                            {{ song.label }}
                          </n-radio>
                        </n-space>
                      </n-radio-group>
                    </NFormItem>
                    <NFormItem label="类别" path="type_id">
                      <n-radio-group v-model:value="modalForm.type_id" name="radiogroup">
                        <n-space>
                          <n-radio
                            v-for="song in data.sltypeData"
                            :key="song.value"
                            :value="song.value"
                          >
                            {{ song.label }}
                          </n-radio>
                        </n-space>
                      </n-radio-group>
                    </NFormItem>
                    <NFormItem label="开始预约时间" path="start_time">
                      <n-date-picker
                        v-model:formatted-value="modalForm.start_time"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetime"
                        placeholder="选择开始时间"
                        clearable
                      />
                    </NFormItem>
                    <NFormItem label="预约截止时间" path="end_time">
                      <n-date-picker
                        v-model:formatted-value="modalForm.end_time"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetime"
                        placeholder="选择结束时间"
                        clearable
                      />
                    </NFormItem>
                    <NFormItem label="参与人数" path="number">
                      <NInputNumber
                        style="width: 200px"
                        v-model:value="modalForm.number"
                        clearable
                        placeholder="输入参与人数"
                        :default-value="0"
                      />
                    </NFormItem>
                    <NFormItem label="显示增加人数" path="show_add">
                      <NInputNumber
                        style="width: 200px"
                        v-model:value="modalForm.show_add"
                        clearable
                        placeholder="输入显示增加人数"
                        :default-value="0"
                      />
                    </NFormItem>
                    <NFormItem label="是否可带人" path="is_accompany">
                      <NSwitch
                        v-model:value="modalForm.is_accompany"
                        :checked-value="true"
                        :unchecked-value="false"
                        :default-value="false"
                        ><template #checked>是</template><template #unchecked>否</template>
                      </NSwitch>
                    </NFormItem>
                    <NFormItem label="是否品牌联名" path="is_brand">
                      <NSwitch
                        v-model:value="modalForm.is_brand"
                        :checked-value="true"
                        :unchecked-value="false"
                        :default-value="false"
                        ><template #checked>是</template><template #unchecked>否</template>
                      </NSwitch>
                    </NFormItem>
                    <NFormItem label="控制每月次数" path="times">
                      <NSwitch
                        v-model:value="modalForm.times"
                        :checked-value="true"
                        :unchecked-value="false"
                        :default-value="false"
                        ><template #checked>是</template><template #unchecked>否</template>
                      </NSwitch>
                    </NFormItem>
                    <NFormItem label="是否需要泊车" path="need_parking">
                      <NSwitch
                        v-model:value="modalForm.need_parking"
                        :checked-value="true"
                        :unchecked-value="false"
                        :default-value="false"
                        ><template #checked>是</template><template #unchecked>否</template>
                      </NSwitch>
                    </NFormItem>
                    <NFormItem
                      label="泊车单价 元/小时"
                      path="parking_price"
                      v-if="modalForm.need_parking == 1"
                    >
                      <NInputNumber
                        style="width: 200px"
                        v-model:value="modalForm.parking_price"
                        clearable
                        placeholder="输入泊车单价"
                        :default-value="0"
                      />
                    </NFormItem>
                    <NFormItem label="沙龙描述" path="desc" style="width: 100%">
                      <NInput
                        v-model:value="modalForm.desc"
                        type="textarea"
                        clearable
                        placeholder="请输入沙龙描述"
                      />
                    </NFormItem>
                  </NFlex>
                </n-tab-pane>
              </n-tabs>
            </n-card>
          </NForm>
        </CrudModal>
      </CommonPage>
  <!-- 业务页面 -->
</template>
